package com.ansion.basedb.dao;

import android.content.Intent;
import android.content.SharedPreferences;
import android.text.TextUtils;

import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.ansion.basedb.dao.model.CurrentUser;
import com.ansion.log.VLog;
import com.ansion.utils.ContactUtil;
import com.ansion.utils.ResourceUtils;

import java.util.UUID;


public class LoginedUserMgr {

    private static final String TAG = "LoginedUserMgr";

    // update to mmkv
    // Preference prefix
    private static final String APP_PREF = "CocoApp_Pref";
    private static final String KEY_LOGINEDUSER = "kCocoPre_LoginedUser";
    private static final String KEY_LAST_LOGINEDUSER = "kCocoPre_LastLoginedUser";
    public static final String ACTION_CURRENTUSER_CHANGED = "ACTION_CURRENTUSER_CHANGED";
    private volatile static CurrentUser loginedUser = null;


    public static CurrentUser getCurrentLoginedUser() {
        if (null == loginedUser) {
            synchronized (LoginedUserMgr.class) {
                if (null == loginedUser) {
                    SharedPreferences sp = getSharedPreferences();
                    String strLoginJson = sp.getString(KEY_LOGINEDUSER, "");
                    VLog.stopD("APP_START", "%s getLoginUserJson:%s", "APP_START", strLoginJson);
                    if (TextUtils.isEmpty(strLoginJson)) {
                        if (TextUtils.isEmpty(strLoginJson)) {
                            return null;
                        }
                    }
                    //AZusLog.d(TAG, "getCurrentLoginedUser- strLoginJson" + strLoginJson);
                    loginedUser = CurrentUser.fromJsonString(strLoginJson);
                    VLog.stopD("APP_START", "%s getCurrentLoginedUser parseJson", "APP_START");
                    if (loginedUser != null) {
                        loginedUser.decodeExtraData();
                        ContactUtil.setMyUid(loginedUser.getUserId());
                        ContactUtil.setWebLogin(loginedUser.isWebHasLogin());
                        ContactUtil.setLoginToken(loginedUser.getLoginToken());
                        ContactUtil.setSessionTag(loginedUser.getSessionTag());
                    }
                }
            }
        }

        return loginedUser;
    }

    public static void setCurrentLoginedUser(CurrentUser user) {
        setCurrentLoginedUser(user, false);
    }

    public static void setCurrentLoginedUser(CurrentUser user, boolean isLogout) {
        SharedPreferences sp = getSharedPreferences();
        SharedPreferences.Editor editor = sp.edit();
        if (null != user) {
            if (TextUtils.isEmpty(user.getSessionTag())) {
                user.setSessionTag(UUID.randomUUID().toString());
            }
            String strLoginJson = user.toJsonString();
            editor.putString(KEY_LAST_LOGINEDUSER, strLoginJson);
            editor.putString(KEY_LOGINEDUSER, strLoginJson);
            //AZusLog.d(TAG, "setCurrentLoginedUser kCocoPre_LoginedUser" + strLoginJson);
            loginedUser = user;
            if (!isLogout) {
                ContactUtil.setMyUid(loginedUser.getUserId());
                ContactUtil.setLoginToken(loginedUser.getLoginToken());
                ContactUtil.setSessionTag(loginedUser.getSessionTag());
            }
            //todo update to mmkv
            SharedPreferences mSharedPreferences = ResourceUtils.getSharedPreferences(ResourceUtils.getContext().getPackageName());
            SharedPreferences.Editor mEditor = mSharedPreferences.edit();
            StringBuffer stringBuffer = new StringBuffer();
            stringBuffer.append("c").append("u");
            mEditor.putString(stringBuffer.append("s").append("e").append("r").append("i").append("d").toString(), user.getUserId() + "");
            mEditor.commit();
            editor.commit();

            sendCurrentUserChangeIntent();

            UserFTSHelper.indexUser(user);
        }
    }


    /**
     * 个人信息改变，通知maintab 中的drawer head 更新
     */
    public static void sendCurrentUserChangeIntent() {
        Intent intent = new Intent(ACTION_CURRENTUSER_CHANGED);
        LocalBroadcastManager.getInstance(ResourceUtils.getContext())
                .sendBroadcast(intent);
    }

    public static void removeCurrentUser() {
        SharedPreferences sp = getSharedPreferences();
        SharedPreferences.Editor editor = sp.edit();
        editor.remove(KEY_LOGINEDUSER);
        if (null != loginedUser) {
            String strLoginJson = loginedUser.toJsonString();
            editor.putString(KEY_LAST_LOGINEDUSER, strLoginJson);
            loginedUser.destroy();
            loginedUser = null;
        }
        editor.commit();

        //AZusLog.d(TAG, "remove current user!");
    }

    // 注销后使用，保留了Token
    public static CurrentUser getLastEverLoginedUser() {
        SharedPreferences sp = getSharedPreferences();
        String strLoginJson = sp.getString(KEY_LAST_LOGINEDUSER, "");
        if (TextUtils.isEmpty(strLoginJson)) {
            return null;
        }
        CurrentUser cUser = CurrentUser.fromJsonString(strLoginJson);
        return cUser;
    }


    public static String getLastEverLoginedTokenMemory() {
        CurrentUser lastUser = getLastEverLoginedUser();
        return lastUser == null ? null : lastUser.getLoginTokenMemory();
    }


    public static String getLastEverLoginedUserId() {
        CurrentUser lastUser = getLastEverLoginedUser();
        return lastUser == null ? null : String.valueOf(lastUser.getUserId());
    }

    public static boolean isLastInstalled() {
        CurrentUser lastUser = getLastEverLoginedUser();
        if (null != lastUser) {
            return false;
        }
        lastUser = getCurrentLoginedUser();
        if (null != lastUser) {
            return false;
        }
        return true;
    }

    public static void clear() {
        SharedPreferences sp = getSharedPreferences();
        SharedPreferences.Editor editor = sp.edit();
        editor.clear();
        editor.commit();
    }

    private static volatile SharedPreferences mSharedPreferences;

    private static SharedPreferences getSharedPreferences() {
        if (mSharedPreferences == null) {
            synchronized (LoginedUserMgr.class) {
                if (mSharedPreferences == null)
                    mSharedPreferences = ResourceUtils.getSharedPreferences(APP_PREF);
            }
        }
        return mSharedPreferences;
    }

    public static long getUserId() {
        CurrentUser currentUser = getCurrentLoginedUser();
        if (null == currentUser) {
            return ContactUtil.INVALID_ID;
        }
        return currentUser.getUserId();
    }

    public static String getUcId() {
        CurrentUser currentUser = getCurrentLoginedUser();
        if (null == currentUser) {
            return ContactUtil.INVALID_ID + "";
        }
        return currentUser.getUcid();
    }

    public static boolean isRealVip() {
        CurrentUser currentUser = getCurrentLoginedUser();
        if (null == currentUser) {
            return false;
        }
        return currentUser.isRealVip();
    }

    public static boolean isRealBadgeWallet() {
        CurrentUser currentUser = getCurrentLoginedUser();
        if (null == currentUser) {
            return false;
        }
        return currentUser.isRealBadgeWallet();
    }
}
